package cn.wolfcode.wolf2w.service.impl;


import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.DestinationQuery;
import cn.wolfcode.wolf2w.repository.DestinationRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class DestinationServiceImpl implements IDestinationService {

    @Autowired
    private DestinationRepository repository;
    @Autowired
    private IRegionService regionService;
    @Autowired
    private MongoTemplate template;


    @Override
    public void insert(Destination destination) {
        repository.save(destination);
    }

    @Override
    public void update(Destination destination) {
        repository.save(destination);
    }

    @Override
    public void delete(String... ids) {
        for (String id : ids) {
            repository.deleteById(id);
        }
    }

    @Override
    public Destination get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Destination> listAll() {
        return repository.findAll();
    }

    @Override
    public List<Destination> findById(String rid) {
        // 通过 rid 查询 区域的对象
        Region region = regionService.get(rid);
        // 通过区域对象的 id集合，查询目的地对象集合
        List<String> ids = region.getRefIds();
        List<Destination> destinations = repository.findByIdIn(ids);
        return destinations;
    }

    @Override
    public Page<Destination> query(DestinationQuery qo) {
        Query query = new Query();
        if (StringUtils.hasLength(qo.getKeyword())){
            query.addCriteria(Criteria.where("name").regex(qo.getKeyword()));
        }
        // 如果parentID 不为 null，目的地
        if (StringUtils.hasLength(qo.getParentId())){
            query.addCriteria(Criteria.where("parentId").is(qo.getParentId()));
        }else{  // 为null，查询的是根
            query.addCriteria(Criteria.where("parentId").is(null));
        }
        long count = template.count(query, Destination.class);
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.ASC,"_id");
        query.with(pageable);
        List<Destination> list = template.find(query, Destination.class);
        return new PageImpl<>(list,pageable,count);
    }

    @Override
    public List<Destination> queryToasts(String destId) {
        List<Destination> list = new ArrayList<>();
        /*createToasts(list,destId);*/
        // 如果 id 有长度，去查询，将对象存入到集合中，直到id为空
        while (StringUtils.hasLength(destId)){
            Destination dest = this.get(destId);
            list.add(dest);
            destId = dest.getParentId();
        }
        Collections.reverse(list);
        return list;
    }

    public void createToasts(List<Destination> list, String destId){
        // 根 >> 中国 >> 广东 >> 广州
        // 如果为 null 表示是根，返回
        if (!StringUtils.hasLength(destId)){
            return;
        }
        Destination dest = this.get(destId);
        list.add(dest);
        if (StringUtils.hasLength(dest.getParentId())){
            createToasts(list,dest.getParentId());
        }
    }

    @Override
    public List<Destination> queryDestByRegionIdForApi(String rid) {
        List<Destination> list = new ArrayList<>();
        // rid 为 -1,国内，list存储的该区域下省份区域等对象
        if ("-1".equals(rid)){
            list = repository.findByParentName("中国");
        }else { // 国外
            list = this.findById(rid);
        }
        // 使用分页的方式，一个集合最多 只显示 5条数据
        Pageable pageable = PageRequest.of(0,5);
        // 循环省份对象，获取省份下的城市（目的地的子目的地）
        for (Destination destination : list) {
            List<Destination> childrenDest = repository.findByParentId(destination.getId(),pageable);
            destination.setChildren(childrenDest);
        }
        if (list.size() > 5){
            list.subList(0,5);
        }
        return list;
    }

    @Override
    public Destination queryName(String keyword) {
        return repository.findByName(keyword);
    }


}
